import store from '@/store'

import {
	getBasicUserApi,
	getUserApi,
	checkLogin,
	getRoleRealApi
} from '@/api/system'
import { postWxCode } from '@/api/login'

import util from './util'

/**
 * 获取用户基本信息
 * @parmas id为用户id
 * @parmas update为true时会重新触发请求，重置vuex的数据
 */
export async function getBasicUser(id, update) {
	console.log('auth', id)
	if (!id) {
		return false
	}
	const params = {
		owner_user_id: id
	}

	let userInfo = store.getters.getBasicUser
	if (!util.isEmpty(userInfo) && !update) {
		return userInfo
	}
	await getBasicUserApi(params).then(res => {
		userInfo = res.data
		store.dispatch('setBasicUser', userInfo)
	}).catch(() => {
		return false
	})

	return userInfo
}

/**
 * 获取后台用户信息
 * @parmas update为true时会重新触发请求，重置vuex的数据
 */
export async function getUser(update) {
	let userInfo = store.getters.getUser
	if (!util.isEmpty(userInfo) && !update) {
	  return userInfo
	}
	await getUserApi().then((res) => {
		userInfo = res.data
		store.dispatch('setUser', userInfo)
		uni.setStorageSync('user_id', res.data.user_id)
	}).catch(() => {
		uni.removeStorageSync('token')
		uni.removeStorageSync('user_id')
	})

	return userInfo
}
/**
 * 清除vuex的用户信息,目前包含（basicUser, user）
 * @parmas 暂无，可扩展
 */
export async function resetAllUser() {
	await store.dispatch('delBasicUser')
	await store.dispatch('delUser')
	return true
}

// 获取用户认证信息
export async function getRoleReal() {
	let roleReal = store.getters.getRoleReal
	if (roleReal) {
	  return roleReal
	}
	const params = {}
	await getRoleRealApi(params).then((res) => {
		roleReal = res.data.roleRealInfo
		store.commit('FETCH_ROLE_REAL', {
		  roleReal
		})
	}).catch(() => {
		return false
	})

	return roleReal
}

/**
 * 微信登陆
 * @parmas update为true时会重新触发请求，重置vuex的数据
 */
// let wxLoginFrist = true
export async function wxLoginFn(update) {
	let dataInfo = null
	let loginInfo = store.state.login.loginInfo
	if (!util.isEmpty(loginInfo) && !update) {
		return loginInfo
	}

	// wxLoginFrist = false
	let getObj = await new Promise(resolve => {
		uni.login({
			provider: 'weixin',
			success: res => {
				uni.setStorageSync('code', res.code)
				console.log(res.code, 'res.code')
				resolve(res)
			}
		})
	})

	await postWxCode({ code: getObj.code }).then(subRes => {
		const { openid, session_key, unionid } = subRes.data
		dataInfo = subRes.data
		store.commit('setLoginInfo', {
			openid,
			session_key,
			unionid
		  })
	})

	return dataInfo
}

/**
 * 获取检查是否登录
 */
export async function checkLoginFn() {
	let status = false
	await checkLogin().then((res) => {
	  if (res.status === 'success') {
			status = true
	  } else {
			uni.removeStorageSync('token')
			uni.removeStorageSync('user_id')
	  }
	}).catch(() => {
		uni.removeStorageSync('token')
		uni.removeStorageSync('user_id')
		uni.removeStorageSync('wxMobile')
	})

	return status
}

export default {
	getBasicUser,
	getUser,
	resetAllUser,
	checkLoginFn,
	getRoleReal
}

